package com.anavigate;

import java.io.InputStream;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Service;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;


public class NetManager extends Service
{
	private static final String TAG = "NetManager";
	private static final String MAPHOST = "http://tile.openstreetmap.org/";
	private static final String HARDLINK =
		"http://tile.openstreetmap.org/12/2047/1362.png";
	public  static final  String BROADCAST_ACTION=
		"com.anavigate.MapUpdate";
	private static final int ZOOM = 12; 
	private LocationManager mgr=null;
	private HttpClient client = null;
	private final Binder binder=new LocalBinder();
	private Intent broadcast = new Intent(BROADCAST_ACTION);
	private Bitmap	mBitmap = null;
	/**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */
	public class LocalBinder extends Binder {
        NetManager getService() {
            return (NetManager.this);
        }
    }
	public void onCreate()
	{
		client = new DefaultHttpClient();
		mgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,
								   0, 0, onLocationChange);
		Log.i(TAG, " onCreate completed...");
	}
	public void onDestroy()
	{
		super.onDestroy();
		mgr.removeUpdates(onLocationChange);
	}
	public IBinder onBind(Intent intent)
	{
		Log.i(TAG,"OnBind()");
		return (binder);
	}
	public Bitmap GetMapPicture()
	{
		return mBitmap;
	}
	private void updateMap(Location loc) {
		new FetchMapTask().execute(loc);
	}
	class FetchMapTask extends AsyncTask<Location, Void, Void> 
	{
		@Override
		protected Void doInBackground(Location... locs) {
			Location loc=locs[0];
			 
			String url = HARDLINK; //calculateTile(loc,ZOOM);
			HttpGet getMethod=new HttpGet(url);
			try {
				Log.i(TAG,"Trying  to download file" + url);
							
				HttpResponse res = client.execute(getMethod);
				InputStream data = res.getEntity().getContent();
				Log.i(TAG,"Downloaded in stream");
				mBitmap = BitmapFactory.decodeStream(data);
				if(mBitmap != null)
				{
					Log.i(TAG,"Decoded to bitmap");
				}
				Log.i(TAG,"Sending broadcast message...");
				sendBroadcast(broadcast);
				data.close();
				}
			catch (Throwable t) {
				android.util.Log.e("NetManager","Exception in updateForecast()", t);
			}
			finally{
				
			}
			
			
			return(null);
		}
		@Override
		protected void onProgressUpdate(Void... unused) {
			// not needed here
		}
		
		@Override
		protected void onPostExecute(Void unused) {
			// not needed here
		}
    }
	LocationListener onLocationChange=new LocationListener() {
			public void onLocationChanged(Location location) {
				Log.i(TAG,"onLocationChange :Longitude "+
						  location.getLongitude()+"Latitude"+ location.getLatitude());
				updateMap(location);
				Log.i(TAG,"current location change...");
			}
			public void onProviderDisabled(String provider) {
				// required for interface, not used
			}
			public void onProviderEnabled(String provider) {
				// required for interface, not used
			}
		
			public void onStatusChanged(String provider, int status,
																	Bundle extras) {
			// required for interface, not used
			}
	};
	
	private String calculateTile(Location loc, final int zoom )
	{
		Log.i(TAG,"calculateTile :Longitude "+
			  loc.getLongitude()+"Latitude"+ loc.getLatitude());
		int xtile = (int)Math.floor( (loc.getLongitude()+ 180) / 360 * (1<<zoom) ) ;
		int ytile = (int)Math.floor( (1 - Math.log(Math.tan(Math.toRadians(loc.getLatitude())) 
					+ 1 / Math.cos(Math.toRadians(loc.getLatitude()))) / Math.PI) / 2 * (1<<zoom) ) ;
		return (MAPHOST + "" + zoom + "/" + xtile + "/" + ytile +".png");
	}
	
}